/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pt.mleiria.generator;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import pt.mleiria.algorithm.SymmetricCipher;


/**
 *
 * @author NB13712
 */
public class KeyGen {

    private String algorithm;
    private String provider;
    private Key key;
    
    public KeyGen() {
    }
    
    public Key getKey() throws NoSuchAlgorithmException, NoSuchProviderException{
        if(null == algorithm || algorithm.isEmpty()){
            throw new IllegalArgumentException("Must choose an algorithm");
        }
        KeyGenerator generator;
        if(null == provider || provider.isEmpty()){
            generator = KeyGenerator.getInstance(algorithm);
        }else{
            generator = KeyGenerator.getInstance(algorithm, provider);
        }
        
        generator.init(new SecureRandom());
        key = generator.generateKey();
        return key;
    }
    /**
     * Creates a DES key from an array of bytes
     * @param input
     * @param offset
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws InvalidKeySpecException 
     */
    public SecretKey makeDESKey(final byte[] input, final int offset) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException{
        SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
        KeySpec keySpec = new DESKeySpec(input, offset);
        return factory.generateSecret(keySpec);
    }
    /**
     * Translate a DES key into an array of bytes
     * @param desKey
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException 
     */
    public byte[] makeBytesFromDESKey(final SecretKey desKey) throws NoSuchAlgorithmException, InvalidKeySpecException{
        final SecretKeyFactory desFactory = SecretKeyFactory.getInstance(algorithm);
        final DESKeySpec spec = (DESKeySpec)desFactory.getKeySpec(desKey, DESKeySpec.class);
        return spec.getKey();
    }

    public String getAlgorithm() {
        return algorithm;
    }

    public void setAlgorithm(SymmetricCipher algorithm) {
        this.algorithm = algorithm.value();
    }

    public String getProvider() {
        return provider;
    }

    public void setProvider(String provider) {
        this.provider = provider;
    }
    
    
    
    
}
